'use strict';

const Service = require('egg').Service;
const uuidv4 = require('uuid/v4');
const OSS = require('ali-oss');


class ALiService extends Service {

  /**
   * 签名，客户端使用
   */
  async ossSign() {
    const uuid = uuidv4()
    const dateStr = this.ctx.helper.formatDate(new Date(), 'YYYY-MM-DD_HH:mm:ss');
    const client = this.client()
    const { ossRole, TokenExpireTime, bucket, cdn } = this.app.config.ali;
    const result = await client.assumeRole(ossRole, null, TokenExpireTime)
    const data = {
      ...result.credentials,
      bucket,
      cdn
    }
    return {
      ...data,
      uuid,
      dateStr
    }
  }

  /**
   * 创建OSS对象
   * @param {*} bucket 块名称
   */
  client() {
    const { accessKeySecret, accessKeyId } = this.app.config.ali;
    return new OSS.STS({
      accessKeyId: accessKeyId,
      accessKeySecret: accessKeySecret
    });
  }

  // =================== 服务款使用 ======================
  getOSS() {
    const { bucket, region, admin } = this.app.config.ali;
    return OSS({
      accessKeyId: admin.accessKeyId,
      accessKeySecret: admin.accessKeySecret,
      bucket: bucket,
      region: region
    });
  }

  /**
   * 删除操作
   * @param {*} fileName 文件名称
   * @param {*} bucket 块名称
   */
  async ossDelete(fileName, bucket = 'ybweb') {
    const client = this.getOSS(bucket);
    return await client.delete(fileName);
  }

  /**
   * 查找文件列表
   * @param {*} prefix 要查找的文件路径前缀
   * @param {*} lastKey 上一个文件的路径(查找的列表为这个路径之后的数据)
   * @param {*} pageSize pageSize=20 分页大小
   */
  async ossList(prefix, lastKey, pageSize = 20) {
    const client = this.getOSS();
    // 不带任何参数，默认最多返回1000个文件
    const data = await client.list({
      prefix,
      marker: lastKey,
      'max-keys': pageSize,
    });
    if (!(data.objects instanceof Array)) {
      return [];
    }
    const { cdn } = this.app.config.ali;
    data.objects.forEach(item => {
      item.cdnUrl = `${cdn}/${item.name}`;
    });
    return data.objects;
  }
}

module.exports = ALiService;
